import router from "@/router";
import store from "@/store";
import axios from "axios";
//引入elementui中的message组件
import { Message } from "element-ui";
const request = axios.create({
  // baseURL: "/api",
  // 在不同的环境下基地址不同
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10 * 1000
})

//请求拦截器
request.interceptors.request.use(config => {
  //注入token
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  //返回config
  return config

}, err => Promise.reject(err))

//响应拦截器
request.interceptors.response.use(
  //2xx给的响应
  (response) => {
    const { data, success, message } = response.data
    // console.log(data, success, message)
    if (success) return data
    Message.error(message)
    return Promise.reject(new Error(message))
  },
  async (error) => {
    if (error.response?.status === 401) {
      Message.warning('token失效了 请重新登录')
      //登出
      await store.dispatch("user/logout");
      //跳到登录页面
      router.push('/login')
      //返回错误
      return Promise.reject(error)
    }

    Message.error('服务器访问失败')
    return Promise.reject(error)
  }

)



//抛出request
export default request